package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.dubbo.mapper.SoulOptionMapper;
import com.tanhua.dubbo.mapper.SoulQuestionMapper;
import com.tanhua.dubbo.mapper.SoulTestMapper;
import com.tanhua.model.pojo.TestOption;
import com.tanhua.model.pojo.TestQuestion;
import com.tanhua.model.pojo.Test;
import com.tanhua.model.vo.SoulVo;
import com.tanhua.model.vo.TestQuestionVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class SoulTestApiImpl implements SoulTestApi {
    @Autowired
    private SoulTestMapper soulTestMapper;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Autowired
    private SoulOptionMapper soulOptionMapper;

    @Override
    public List<SoulVo> findTest() {
        List<SoulVo> vos = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            Test test = soulTestMapper.findRandomTest(i);
            List<TestQuestion> questions = soulQuestionMapper.findRandomQuestion(test.getStar());
            Collections.shuffle(questions);
            List<TestQuestionVo> testQuestionVos = new ArrayList<>();
            for (TestQuestion question : questions) {
                List<TestOption> options = soulOptionMapper.selectList(Wrappers.lambdaQuery(TestOption.class).eq(TestOption::getQuestionId, question.getId()));
                TestQuestionVo questionVo = TestQuestionVo.init(question, options);
                testQuestionVos.add(questionVo);
            }
            SoulVo vo = SoulVo.init(test, testQuestionVos);
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public Integer getScore(List<String> optionId) {
        List<TestOption> options = soulOptionMapper.selectList(Wrappers.lambdaQuery(TestOption.class).in(TestOption::getId, optionId));
        Integer all = 0;
        for (TestOption option : options) {
            all += option.getScore();
        }
        return all;
    }
}
